package com.zsp.coupon.service.imp;

import com.zsp.coupon.dao.CouponTemplateDao;
import com.zsp.coupon.entity.CouponTemplate;
import com.zsp.coupon.exception.CouponException;
import com.zsp.coupon.service.IAsyncService;
import com.zsp.coupon.service.IBuildTemplateService;
import com.zsp.coupon.vo.TemplateRequst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <h1>构建优惠券模板接口实现</h1>
 * Created by zsp.
 */

@Service
public class IBuildTemplateServiceImpl implements IBuildTemplateService {

    private IAsyncService asyncService;

    /** 异步服务 */
    private  final CouponTemplateDao templateDao;

    @Autowired
    public IBuildTemplateServiceImpl(IAsyncService asyncService, CouponTemplateDao templateDao) {
        this.asyncService = asyncService;
        this.templateDao = templateDao;
    }


    /**
     * <h2>创建优惠券模板</h2>
     * @param requst {@link TemplateRequst} 模板信息请求对象
     * @return {@link CouponTemplate} 优惠券模板实体
     */
    @Override
    public CouponTemplate buildTemplate(TemplateRequst requst) throws CouponException {
        //参数合法检验
        if (! requst.validate()){
            throw  new CouponException("BuildTemplate Param is  not Vaild");
        }
        //判断同名的优惠卷是否存在
        if (null != templateDao.findByName(requst.getName())){
            throw  new CouponException("Exist same name is  template");
        }

        //构造 CouponTemplate 并保存到数据库中
        CouponTemplate template=requestToTemplate(requst);
         template=templateDao.save(template);

         //根据优惠卷异步生成优惠卷码
        asyncService.asyncConstructCouponByTemplate(template);
        return template;
    }

    /**
     * <h2>将 TemplateRequest 转换为 CouponTemplate</h2>
     * */
    private CouponTemplate requestToTemplate(TemplateRequst requst){
        return  new CouponTemplate(requst.getName(),
                requst.getLogo(),
                requst.getDesc(),
                requst.getCategory(),
                requst.getProductLine(),
                requst.getCount(),
                requst.getUserId(),
                requst.getTarget(),
                requst.getRule());
    }

}
